#include <linux/jiffies.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>

#include "stm32f1xx.h"

extern UART_HandleTypeDef huart1;
static inline int serial_putc(unsigned char ch) {
    unsigned timeout = 0xffff;
    HAL_UART_Transmit(&huart1, &ch, 1, timeout);
    return timeout ? 0 : -1;
}

static inline void serial_write(const char *s, unsigned n) {
    while (*s && n-- > 0) {
        if (*s == '\n') serial_putc('\r');
        serial_putc(*s);
        s++;
    }
}

void serial_printf(const char *fmt, ...) {
    va_list ap;
    char buf[512];
    int n;

    va_start(ap, fmt);
    n = vsnprintf(buf, sizeof(buf), fmt, ap);
    va_end(ap);

    serial_write(buf, n);
}

void _print_current_time(void) {
    unsigned long msecs = jiffies_to_msecs(jiffies);
    unsigned long secs = msecs / 1000;
    unsigned long msec = msecs % 1000;
    serial_printf("[%5lu.%03lu]", secs, msec);
}

const char *_split_file_name(const char *fileName) {
    const char *pChar = fileName;
    pChar = (strrchr(pChar, '/') ? strrchr(pChar, '/') + 1 : (strrchr(pChar, '\\') ? strrchr(pChar, '\\') + 1 : pChar));
    return pChar;
}
